package handlers

import (
	"strconv"
	"sysu-giep/internal/api/middleware"
	"sysu-giep/internal/service"
	"sysu-giep/pkg/logger"
	"sysu-giep/pkg/response"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

var notificationService *service.NotificationService

// InitNotificationHandlers 初始化通知处理器
func InitNotificationHandlers(ns *service.NotificationService) {
	notificationService = ns
}

// GetNotifications 获取通知列表
// @Summary 获取通知列表
// @Description 获取当前用户的通知列表
// @Tags 通知
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param page query int false "页码" default(1)
// @Param size query int false "每页大小" default(10)
// @Success 200 {object} response.PageResponse{data=[]map[string]interface{}} "通知列表"
// @Router /notifications [get]
func GetNotifications(c *gin.Context) {
	userID := middleware.GetCurrentUserID(c)
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "10"))

	// 参数验证
	if page < 1 {
		page = 1
	}
	if size < 1 || size > 100 {
		size = 10
	}

	logger.Info("获取通知列表", zap.Uint64("user_id", uint64(userID)), logger.Int("page", page), logger.Int("size", size))

	notifications, total, err := notificationService.GetNotificationsById(userID, page, size)
	if err != nil {
		logger.ErrorLog("获取通知列表失败", zap.Error(err))
		response.InternalServerError(c, "获取通知列表失败: "+err.Error())
		return
	}

	response.PageSuccess(c, notifications, total, page, size)
}

// MarkNotificationAsRead 标记通知为已读
// @Summary 标记通知为已读
// @Description 标记指定通知为已读状态
// @Tags 通知
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param id path int true "通知ID"
// @Success 200 {object} response.Response
// @Failure 400 {object} response.Response
// @Router /notifications/{id}/read [put]
func MarkNotificationAsRead(c *gin.Context) {
	userID := middleware.GetCurrentUserID(c)
	idStr := c.Param("id")

	logger.Info("标记通知为已读", zap.Uint64("user_id", uint64(userID)), logger.String("notification_id", idStr))

	if err := notificationService.MarkNotificationAsRead(userID, idStr); err != nil {
		logger.ErrorLog("标记通知为已读失败", zap.Error(err))
		response.InternalServerError(c, "标记通知为已读失败: "+err.Error())
		return
	}

	response.SuccessWithMessage(c, "通知已标记为已读", nil)
}

// GetUnreadNotificationCount 获取未读通知数量
// @Summary 获取未读通知数量
// @Description 获取当前用户的未读通知数量
// @Tags 通知
// @Accept json
// @Produce json
// @Security BearerAuth
// @Success 200 {object} response.Response{data=map[string]interface{}} "未读通知数量"
// @Router /notifications/unread/count [get]
func GetUnreadNotificationCount(c *gin.Context) {
	userID := middleware.GetCurrentUserID(c)

	logger.Info("获取未读通知数量", zap.Uint64("user_id", uint64(userID)))

	count, err := notificationService.GetUnreadNotificationCount(userID)
	if err != nil {
		logger.ErrorLog("获取未读通知数量失败", zap.Error(err))
		response.InternalServerError(c, "获取未读通知数量失败: "+err.Error())
		return
	}

	response.Success(c, gin.H{
		"count": count,
	})
}
